package com.liwq.base.sync;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author : liwq
 * @version : 1.0
 * @date : 2023/2/21
 **/

class Mycache {


    private volatile Map<String, Object> map = new HashMap<>();

    //private Lock lock = new ReentrantLock(); //并不能满足并发读取

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, Object o)  {
        lock.writeLock().lock();
        System.out.println(Thread.currentThread().getName() + "正在写入" + key);
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        map.put(key, o);
        System.out.println(Thread.currentThread().getName() + "写入完成" + key);
        lock.writeLock().unlock();
    }

    public void get(String key)  {
        lock.readLock().lock();
        System.out.println(Thread.currentThread().getName() + "正在读取" + key);
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取完成"+o);
        lock.readLock().unlock();
    }


}

public class ReadWriteLockTest {

    public static void main(String[] args) {

        Mycache mycache = new Mycache();

        for (int i = 0; i <=5 ; i++) {
            final int finalI = i;
            new Thread(()->{
                mycache.put(finalI +"",finalI+"");
            },String.valueOf(i)).start();
        }


        for (int i = 0; i <=5 ; i++) {
            final int finalI = i;
            new Thread(()->{
                mycache.get(finalI +"");
            },String.valueOf(i)).start();
        }
        
    }
}
